var OrdersModule = function () {

    var editable = function () {

        return {
            init: function () {
            	//格式化金额
            	function fmoney(s, n) {  
            	   if(s == ""|| undefined == s){
            		   return "--";
            	   }
                   n = n > 0 && n <= 20 ? n : 2;  
                   s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";//更改这里n数也可确定要保留的小数位  
                   var l = s.split(".")[0].split("").reverse(),  
                   r = s.split(".")[1];  
                   t = "";  
                   for(i = 0; i < l.length; i++ )  
                   {  
                      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");  
                   }
                   var str = t.split("").reverse().join("") + "." + r.substring(0,2);
                   return str;//保留2位小数  如果要改动 把substring 最后一位数改动就可  
                }
            	
            	//表格初始化
                var oTable = $('#ordersEditable').dataTable({
                    "lengthMenu": [
                        [10, 15, 20, 50],
                        [10, 15, 20, 50]
                    ],
                    "autoWidth":false,
                    "scrollX":true,
                    "displayLength": 10,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "zeroRecords":"数据为空",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info" : "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",    
                        "infoEmpty" : "记录数为0",
                    },
                    "columnDefs": [
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "Edit",
						    "targets": [10]
						}            
                    ],
                    "columns": [
                        { "data": "investorName" ,'sortable': false,"defaultContent": "" },
                       { "data": "mobile" ,'sortable': false,"defaultContent": "" },
                       { "data": "orderAmount" ,'sortable': false,"defaultContent": "" },
                       { "data": "orderTime" ,'sortable': false,"defaultContent": "" },
                       { "data": "state",'sortable': false,"defaultContent": "" },
                       { "data": "evaluaState",'sortable': false,"defaultContent": "" },
                       { "data": "riskDisclosure" ,'sortable': false,"defaultContent": "" },
                       { "data": "state" ,'sortable': false,"defaultContent": "" },
                       { "data": "revisitState" ,'sortable': false,"defaultContent": "" },
                       { "data": "stampAdded" ,'sortable': false,"defaultContent": "" },
                       { "data": "operation" ,'sortable': false,"defaultContent": "" }
                   ],
                   "filter" : false,
                   "processing": false,
                   "serverSide": true,
                   "ajaxSource": ctx + "/publisher/orders/query",
                   "serverMethod": "post",
                   "fnRowCallback" : function(nRow, aData, displayIndex) {
                	   nRow.children[0].id = aData.id;
                	   var investorName = 
                		   "<center>" + aData.investorName + "</center>";
                	   var mobileFormat = aData.mobile;
                	   if (aData.mobile.startsWith('0') == true){
                		   var mobile = 
                    		   "<center>" + aData.mobile.slice(0,4) +"********</center>";
                	   } else {
                		   var mobile = 
                    		   "<center>" + aData.mobile.slice(0,3) +"********</center>";
                	   }
                	  
                	   var orderAmount = 
                		   "<center>"+ fmoney(aData.orderAmount) + "</center>";
                	   var orderTime = "";
                	   if(aData.orderTime.split(' ')[0]== undefined){
                		   orderTime = "<center>--</center>";
                	   }else{
                		   orderTime = "<center>" + aData.orderTime.split(' ')[0] + "</center>";
                	   }
                	   //1已支付2未支付3已兑付4部分支付5已取消6已完成7即将到期8带兑付
                	   var state = aData.state;
                	   var stateFormat = ''
                	   switch(state) {
                	   		case (1):
                	   			stateFormat = "<center>已支付</center>";
                	   			break;
                	   		case (2):
                	   			stateFormat = "<center>未支付</center>";
                	   			break;
                	   		case (3):
                	   			stateFormat = "<center>已兑付</center>";
                	   			break;
                	   		case (4):
                	   			stateFormat = "<center>部分支付</center>";
                	   			break;
                	   		case (5):
                	   			stateFormat = "<center>已取消</center>";
                	   			break;
                	   		case (6):
                	   			stateFormat = "<center>已完成</center>";
                	   			break;
                	   		case (7):
                	   			stateFormat = "<center>即将到期</center>";
                	   			break;
                	   		case (8):
                	   			stateFormat = "<center>待兑付</center>";
                	   			break;
                	   		default:
                	   
                	  }
                	   var operation = "";
                	   var evaluaState = "";
                	   if(aData.evaluaState == 3){
                		   evaluaState = "<center>未测</center>";
                       }else{
                    	   evaluaState = "<center>已测</center>";
                       }
                	   var riskDisclosureSign = "";
                	   if(aData.riskDisclosureSign == undefined || aData.riskDisclosureSign == ""){
                		   riskDisclosureSign = "<center>未签</center>";
                       }else{
                    	   riskDisclosureSign = "<center>已签</center>";
                       }
                	   var revisitState = "-";
                	   var operation = "-";
                	   var stampAdded = "-";
                	   var needRevisit = $('#needRevisit').val();
                	   if(needRevisit == '1'){
                		   if(aData.type == 0){
                    		   if(aData.revisitState == 1 || aData.revisitState == 0){
                    			   revisitState = "<center>未回访</center>";
                        		   operation = operation+"<a class=\"send fa fa-bars fa-paper-plane pull-left\" title=\"发起回访\" href=\"javascript:;\"></a>";
                               }else if(aData.revisitState == 2){
                            	   revisitState = "<center>回访未确认</center>";
                            	   operation = operation+"<a class=\"content fa fa-bars fa-twitch pull-left\" title=\"回访反馈内容\" href=\"javascript:;\"></a>";
                               }else if(aData.revisitState == 3){
                            	   revisitState = "<center>已完成</center>";
                            	   operation = operation+"<a class=\"content fa fa-bars fa-twitch pull-left\" title=\"回访反馈内容\" href=\"javascript:;\"></a>";
                               }
                    	   } else {
                    		   revisitState = "<center>线下订单无需回访</center>";
                    	   }
                    	   
                           if(aData.type == 0){
                        	   if(aData.stampAdded == true){
                        		   stampAdded = "<center>已盖章</center>";
                               }else{
                            	   stampAdded = "<center>未盖章</center>";
                            	   if(aData.revisitState == 3){
                            		   operation = operation+"&nbsp;&nbsp;&nbsp;<a class=\"cachet fa fa-bars fa-paint-brush pull-left\" title=\"加盖公章\" href=\"javascript:;\"></a>";
                            	   }
                               }
                           } else {
                        	   
                           }
                	   }
                	   
                	   var state = "";
                	   if(aData.state == 6 || aData.state == 3 || aData.state == 7 || aData.state == 8){
                		   state = "<center>已签</center>";
                       }else{
                    	   state = "<center>未签</center>";
                    	   operation = "-";
                       }
                	   
                	   $('td:eq(0)', nRow).html(investorName);
                	   $('td:eq(1)', nRow).html(mobile);
                	   $('td:eq(2)', nRow).html(orderAmount);
                	   $('td:eq(3)', nRow).html(orderTime);
                	   $('td:eq(4)', nRow).html(stateFormat);
                	   $('td:eq(5)', nRow).html(evaluaState);
                	   $('td:eq(6)', nRow).html(riskDisclosureSign);
                	   $('td:eq(7)', nRow).html(state);
                	   $('td:eq(8)', nRow).html(revisitState);
                	   $('td:eq(9)', nRow).html(stampAdded);
                	   $('td:eq(10)', nRow).html(operation);
                       return nRow;
                   },
                   "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                   var json = "";
	                   var s;
	                   for (var i = 0; i < dataSet.length; i++) {
	                       s = dataSet[i];
	                   	   if (s.name == 'sEcho') {
	                   		   json = json + '"echo":' + s.value;
		                   } else if (s.name == 'iDisplayStart') {
		                	   json = json + ',"page":' + s.value;
		                   } else if (s.name == 'iDisplayLength') {
		                	   json = json + ',"pageSize":' + s.value;
		                   }
	                   }
	                   
	                   var form = $("form#queryForm").serializeJSON();
                   	   var js = form.replace('}', ',');
                   	   json = js + json +'}';
                       $.ajax({
                       	"contentType":"application/json; charset=UTF-8",
                           "dataType" : 'json',
                           "type" : "POST",
                           "url" : ajaxSource,
                           "data" : json,
                           "success" : fnCallback
                       });
                   },
                });
                
                // 发起回访
                $('#ordersEditable').on("click", "a.send", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    $.teninedialog({
                        title:'系统提示',
                        content:'确认对此订单发起回访?',
                        showCloseButton:false,
                        otherButtons:["确定","取消"],
                        otherButtonStyles:['btn-primary','btn-white'],
                        bootstrapModalOption:{keyboard: true},
                        clickButton:function(sender,modal,index){
                       	 //发起回访
                       	 if(index == 0){
                                $.ajax({
                                	type:"post",
                                    contentType:"application/json; charset=UTF-8",
                                    url: ctx + "/publisher/startCallback/"+id,
                                    dataType:"json",
                                    success: function(msg){
                                   	 $.teninedialog({
                                            title:'系统提示',
                                            content:msg.message,
                                            showCloseButton:false,
                                            otherButtons:["确定"],
                                            otherButtonStyles:['btn-primary'],
                                            bootstrapModalOption:{keyboard: true},
                                            clickButton:function(sender,modal,index){
                                            	location.reload();
                                            }
                                        });
                                    },
                                    error: function (msg) {
                                    	bootbox.alert("服务器出错了,发起回访失败了!");
                                    }
                                });
                       	 }
                       	 $(this).closeDialog(modal); 
                        }
                    });
                }));
                // 回访反馈内容
                $('#ordersEditable').on("click", "a.content", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    $.ajax({
                       	"contentType":"application/json; charset=UTF-8",
                           "type" : "POST",
                           "url" : ctx+'/publisher/reviewCallback/'+id,
                           "success" : function(msg){
                        	   if(msg.code == 0){
                        		   bootbox.alert(msg.message);
                        	   } else {
                        		   $("#revisitBody").empty();// clean
                        		   if(msg.data.investorSign != undefined || msg.data.investorSign == ''){
		                        			msg.data.investorSign = imagePrefix + msg.data.investorSign;
		                        	}
		                           	var tmpl = $("#revisitTemplate").tmpl(msg.data).appendTo("#revisitBody");
		                           	
		                           	var modal = $('#revisitModel').modal('show');
		                           	modal.on("hidden.bs.modal",function(e){
		                           		$(this).removeData();
		                           	});
                        	   }
                           }
                       });
                }));
                // 加盖公章
                $('#ordersEditable').on("click", "a.cachet", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    document.getElementById("electronicSeal_order_id").value = id;
                    var ii = $("#electronicSeal_order_id").val();
                    $("#upload_electronicSeal").click();
                }));
                
                //查询
                $('#queryBtn').click(function(){
                	oTable.fnClearTable();
                });
            }

        };

    }();
    
    return {
        init: function () {
        	editable.init();
        }
    };
}();

//上传电子公章
function uploadElectronicSeal() {
	if (!$("#electronicSeal").val()) {
		bootbox.alert("上传电子公章不能为空！");
		return;
	}
	var id = $("#electronicSeal_order_id").val();
	$.ajaxFileUpload({
			url : ctx + '/publisher/uploadElectronicSeal?id='+id,
			type : 'post',
			secureuri : false,
			fileElementId : 'electronicSeal',
			dataType : 'json',
			success : function(data, status) {
				if (data.code == 1) {
					$('#dsimiss_deal_emp').click();
					$.teninedialog({
                        title:'系统提示',
                        content:'上传电子公章成功！',
                        showCloseButton:false,
                        otherButtons:["确定"],
                        otherButtonStyles:['btn-primary'],
                        bootstrapModalOption:{keyboard: true},
                        clickButton:function(sender,modal,index){
                        	location.reload();
                        }
                    });
				} else {
					bootbox.alert(data.message);
				}
		},
		error : function(msg, status, e) {
			bootbox.alert("上传电子公章失败！");
		}
	});
}